package main

import (
	"github.com/gorilla/websocket"
	"net/http"
)

var (
	upgrader = websocket.Upgrader{
		//遇到跨域问题的时候是允许跨域的
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
)

func wsHandler(w http.ResponseWriter, r *http.Request) {
	var (
		conn *websocket.Conn
		err  error
		//message int
		data []byte
	)

	//w.Write([]byte("hello")) 应答
	if conn, err = upgrader.Upgrade(w, r, nil); err != nil { //这步调用就完成了底层http应答
		return
	}
	for {
		if _, data, err = conn.ReadMessage(); err != nil {
			goto ERR
		}
		if err = conn.WriteMessage(websocket.TextMessage, data); err != nil {
			goto ERR
		}
	}
ERR: //做一个标签，其他地方可以调用这个标签。
	conn.Close()
}
func wsHandler2(w http.ResponseWriter, r *http.Request) {
	var (
		wsConn *websocket.Conn
		err    error
		//message int
		conn impl.Connection
	)

	//w.Write([]byte("hello")) 应答
	if wsConn, err = upgrader.Upgrade(w, r, nil); err != nil { //这步调用就完成了底层http应答
		return
	}
	if conn, err = impl.InitConnection(wsConn); err != nil {
		goto ERR
	}

	/*	for {
		if _, data, err = conn.ReadMessage(); err != nil {
			goto ERR
		}
		if err = conn.WriteMessage(websocket.TextMessage, data); err != nil {
			goto ERR
		}
	}*/
ERR: //做一个标签，其他地方可以调用这个标签。
	//conn.Close()  todo:做一个关闭连接操作
}
func main() {
	http.HandleFunc("/ws", wsHandler)
	http.ListenAndServe("0.0.0.0:7777", nil) //监听一个端口并且对外提供服务
	//test
}
